"""
增强记忆系统模块 - 简化版本
Enhanced Memory System for DingDing Agent

提供核心记忆增强功能：
- 智能查询重写（代词消解、上下文补全）
- 分层记忆存储（短期、长期记忆）
- LangGraph深度集成（增强工作流）
- 性能优化（混合缓存、批处理）

已简化移除：
- 用户画像记忆（过度复杂）
- 知识记忆（未充分利用）
- 上下文记忆（功能重叠）
"""

__version__ = "1.0.0"
__author__ = "Enhanced Memory System"

# 核心架构
from .memory_architecture import (
    EnhancedMemoryArchitecture,
    MemoryItem,
    MemoryType,
    MemoryPriority,
    MemoryConfig,
    MemoryMetrics,
    ContextReference
)

# 查询重写
from .query_rewriter import (
    QueryRewriter,
    QueryRewriteResult,
    ContextEntity
)

# 记忆管理器 - 简化版本
from .memory_managers import (
    BaseMemoryManager,
    ShortTermMemoryManager,
    LongTermMemoryManager
    # 已移除未充分利用的管理器：
    # UserProfileManager - 过度复杂
    # ContextManager - 功能重叠
)

# 增强记忆类
from .enhanced_memory_class import EnhancedMemoryClass

# LangGraph集成
from .langgraph_integration import (
    EnhancedAgentState,
    MemoryEnhancedNode,
    QueryRewriteNode,
    MemoryContextNode,
    EnhancedSupervisorNode,
    Text2SQLEnhancedNode,
    EnhancedWorkflowBuilder
)

# 性能优化
from .performance_optimization import (
    CacheItem,
    LRUCache,
    # HybridCacheManager 已移除 - 过度设计的缓存管理器
    AsyncBatchProcessor,
    ExtensibilityInterface,
    RAGInterface
)

# 集成智能体类
from .integrated_agent_class import (
    EnhancedAgentClass,
    create_enhanced_agent
)

# 便捷导入
__all__ = [
    # 核心架构
    "EnhancedMemoryArchitecture",
    "MemoryItem",
    "MemoryType", 
    "MemoryPriority",
    "MemoryConfig",
    "MemoryMetrics",
    "ContextReference",
    
    # 查询重写
    "QueryRewriter",
    "QueryRewriteResult",
    "ContextEntity",
    
    # 记忆管理器 - 简化版本
    "BaseMemoryManager",
    "ShortTermMemoryManager",
    "LongTermMemoryManager",
    # 已移除：
    # "UserProfileManager" - 过度复杂
    # "ContextManager" - 功能重叠
    
    # 增强记忆类
    "EnhancedMemoryClass",
    
    # LangGraph集成
    "EnhancedAgentState",
    "MemoryEnhancedNode",
    "QueryRewriteNode",
    "MemoryContextNode", 
    "EnhancedSupervisorNode",
    "Text2SQLEnhancedNode",
    "EnhancedWorkflowBuilder",
    
    # 性能优化
    "CacheItem",
    "LRUCache",
    # "HybridCacheManager", # 已移除
    "AsyncBatchProcessor",
    "ExtensibilityInterface",
    "RAGInterface",
    
    # 集成智能体类
    "EnhancedAgentClass",
    "create_enhanced_agent"
]

# 版本信息
def get_version():
    """获取版本信息"""
    return __version__

def get_features():
    """获取功能特性列表"""
    return [
        "智能查询重写 - 代词消解和上下文补全",
        "分层记忆存储 - 短期、长期、用户画像、上下文记忆",
        "LangGraph深度集成 - 增强工作流和节点",
        "性能优化 - 混合缓存和异步批处理",
        "扩展性设计 - 插件系统和RAG接口预留",
        "向后兼容 - 与现有AgentClass完全兼容"
    ]

def print_info():
    """打印模块信息"""
    print(f"Enhanced Memory System v{__version__}")
    print("=" * 50)
    print("功能特性:")
    for i, feature in enumerate(get_features(), 1):
        print(f"{i}. {feature}")
    print("=" * 50)

# 快速开始示例
def quick_start_example():
    """快速开始示例代码"""
    example_code = '''
# 快速开始示例
import asyncio
from enhanced_memory import create_enhanced_agent_async

async def main():
    # 创建增强智能体
    agent = await create_enhanced_agent_async()
    
    # 进行对话
    response = await agent.run_agent("你好，我叫张三", user_id="user123")
    print(response['output'])
    
    # 测试查询重写
    response = await agent.run_agent("那明天的呢？", user_id="user123")
    print(response['output'])
    
    # 获取性能统计
    stats = await agent.get_performance_stats()
    print(f"记忆系统: {stats['memory_system']}")

# 运行示例
asyncio.run(main())
'''
    return example_code

# 模块初始化检查
def check_dependencies():
    """检查依赖包"""
    required_packages = [
        "langchain",
        "langchain_openai", 
        "langchain_core",
        "langchain_community",
        "langgraph",
        "redis",
        "pydantic",
        "numpy"
    ]
    
    missing_packages = []
    
    for package in required_packages:
        try:
            __import__(package)
        except ImportError:
            missing_packages.append(package)
    
    if missing_packages:
        print(f"⚠️  缺少依赖包: {', '.join(missing_packages)}")
        print("请运行: pip install " + " ".join(missing_packages))
        return False
    
    print("✅ 所有依赖包已安装")
    return True

# 配置验证
def validate_config():
    """验证配置"""
    import os
    
    required_env_vars = [
        "OPENAI_API_KEY",
        "REDIS_URL"
    ]
    
    missing_vars = []
    
    for var in required_env_vars:
        if not os.getenv(var):
            missing_vars.append(var)
    
    if missing_vars:
        print(f"⚠️  缺少环境变量: {', '.join(missing_vars)}")
        return False
    
    print("✅ 配置验证通过")
    return True

# 健康检查
async def health_check():
    """系统健康检查"""
    print("🔍 增强记忆系统健康检查")
    print("=" * 40)
    
    # 检查依赖
    deps_ok = check_dependencies()
    
    # 检查配置
    config_ok = validate_config()
    
    if not (deps_ok and config_ok):
        print("❌ 健康检查失败")
        return False
    
    try:
        # 测试Redis连接
        import redis.asyncio as redis
        import os
        
        redis_client = redis.from_url(os.getenv("REDIS_URL"))
        await redis_client.ping()
        print("✅ Redis连接正常")
        
        # 测试OpenAI连接
        from langchain_openai import ChatOpenAI
        
        model = ChatOpenAI(
            model=os.getenv("BASE_MODEL", "gpt-4"),
            api_key=os.getenv("OPENAI_API_KEY"),
            base_url=os.getenv("OPENAI_BASE_URL")
        )
        
        # 简单测试
        response = await model.ainvoke("Hello")
        print("✅ OpenAI连接正常")
        
        print("🎉 系统健康检查通过！")
        return True
        
    except Exception as e:
        print(f"❌ 健康检查失败: {e}")
        return False

# 模块加载时的初始化
if __name__ == "__main__":
    print_info()
    print("\n快速开始示例:")
    print(quick_start_example())
else:
    # 静默加载，只在需要时进行检查
    pass
